import { FC, useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { Layout, Input, Button, Card, Space, message } from 'antd';
import { SendOutlined, LoadingOutlined } from '@ant-design/icons';
import { chatApi } from 'services/chat';
import type {
  ChatMessage as ApiChatMessage,
  HistoryConversation,
} from 'types/chat';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { techInsightApi } from 'services';
import MainLayout from 'components/MainLayout';
import { CHAT_API_TOKEN, DIFY_API_URL } from 'constant';

import ChatHistory from './components/ChatHistory';
import ChatMessage from './components/ChatMessage';
import { ChatSession } from './types';

import styles from './AIChat.module.css';

const { Sider, Content } = Layout;

const AIChat: FC = () => {
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [activeSession, setActiveSession] = useState<string>();
  const [historyList, setHistoryList] = useState<HistoryConversation[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 分页参数
  const [hasMore, setHasMore] = useState(false);
  const [pageIds, setPageIds] = useState<string[]>([]); // 保存每页的第一条记录ID
  const [lastId, setLastId] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);

  const username = localStorage.getItem('username') || '';

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [sessions]);

  // 获取当前会话的消息
  const fetchConversationMessages = useCallback(async () => {
    if (!activeSession) return;

    try {
      const res = await chatApi.getConversationMessages({
        conversation_id: activeSession,
        limit: 100,
        user: username,
        first_id: null,
      });

      const formattedMessages: ApiChatMessage[] = [];

      res.data.forEach((msg: any) => {
        // 将获取到的消息转换为正确的格式
        const messages: ApiChatMessage[] = [
          {
            messageId: msg.id + 'user',
            role: 'user',
            content: msg.query,
            timestamp: msg.created_at,
          },
          {
            messageId: msg.id,
            role: 'assistant',
            content: msg.error
              ? '系统调试升级中，请稍后尝试！' || '暂无数据'
              : msg.answer,
            timestamp: msg.created_at,
          },
        ];

        formattedMessages.push(...messages);
      });

      // 更新当前会话的消息
      setSessions((prev) =>
        prev.map((session) => {
          if (session.id === activeSession) {
            return {
              ...session,
              messages: formattedMessages,
              messageCount: formattedMessages.length,
            };
          }
          return session;
        })
      );
    } catch (error) {
      message.error(`获取会话消息失败: ${error}`);
      console.error('获取会话历史消息失败:', error);
    }
  }, [activeSession, username]);

  // 获取当前会话的所有消息
  useEffect(() => {
    fetchConversationMessages();
  }, [activeSession, fetchConversationMessages]);

  // 获取所有会话列表
  const fetchConversations = useCallback(
    async (page: number, direction: 'prev' | 'next' = 'next') => {
      setHistoryLoading(true);

      try {
        let queryLastId = null;

        if (page > 1 && direction === 'next') {
          queryLastId = lastId;
        } else if (direction === 'prev' && page > 1) {
          queryLastId = pageIds[page - 2]; // 获取上一页的最后一条记录ID
        }

        const res = await chatApi.getConversations({
          limit: 20,
          user: username,
          last_id: queryLastId,
        });

        setHistoryList(res.data);

        // 保存所有的会话消息
        setSessions(
          res.data?.map((item: HistoryConversation) => ({
            id: item.id,
            title: item.name,
            time: item.created_at,
            messageCount: 0,
            messages: [],
          }))
        );

        if (res.data.length > 0) {
          // 更新lastId为最后一条记录的id
          setLastId(res.data[res.data.length - 1].id);

          // 保存当前页的最后一条记录的id
          setPageIds((prev) => [
            ...prev.slice(0, page - 1),
            res.data[res.data.length - 1].id,
          ]);
        }

        setHasMore(res.has_more);
      } catch (error) {
        console.error('获取会话列表失败:', error);
      } finally {
        setHistoryLoading(false);
      }
    },
    [lastId, pageIds, username]
  );

  useEffect(() => {
    setLastId(null);
    setPageIds([]);
    fetchConversations(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 处理页面变化
  const handlePageChange = (page: number) => {
    const direction = page > currentPage ? 'next' : 'prev';
    setActiveSession(undefined);
    setCurrentPage(page);
    fetchConversations(page, direction);
  };

  // 创建新会话
  const createNewSession = (firstMessage: string) => {
    const newSession: ChatSession = {
      id: undefined,
      title:
        firstMessage.slice(0, 20) + (firstMessage.length > 20 ? '...' : ''),
      time: new Date().toLocaleString(),
      messageCount: 0, // 初始化为0，因为消息会在handleSend中添加
      messages: [], // 初始化为空数组，消息会在handleSend中添加
    };

    setSessions((prev) => [newSession, ...prev]);
    setActiveSession(newSession.id);
    return newSession;
  };

  // 发送消息
  const handleSend = async () => {
    if (!input.trim()) return;

    setLoading(true);

    try {
      let currentSession = sessions.find((s) => s.id === activeSession);
      if (!currentSession?.id) {
        currentSession = createNewSession(input);
      }
      const isNewSession = !currentSession?.id;

      // 用户消息
      const userMessage: ApiChatMessage = {
        messageId: Date.now().toString(),
        role: 'user',
        content: input,
        timestamp: Math.floor(Date.now() / 1000).toString(),
      };

      // 添加一个空的AI回复消息（带loading状态）
      const pendingAiMessage: ApiChatMessage = {
        messageId: `pending-${Date.now()}`,
        role: 'assistant' as const,
        content: '',
        loading: true,
        timestamp: Math.floor(Date.now() / 1000).toString(),
      };

      // 更新会话，添加两条消息
      setSessions((prev) =>
        prev.map((session) => {
          if (session.id === currentSession?.id) {
            return {
              ...session,
              messageCount: (session.messageCount || 0) + 2,
              messages: [
                ...(session.messages || []),
                userMessage,
                pendingAiMessage,
              ],
            };
          }
          return session;
        })
      );

      let currentMessage = '';

      await fetchEventSource(DIFY_API_URL + '/chat-messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: CHAT_API_TOKEN,
        },
        body: JSON.stringify({
          query: input,
          inputs: {},
          response_mode: 'streaming',
          user: username,
          conversation_id: currentSession?.id || '',
        }),
        onmessage(msg) {
          setInput('');
          setLoading(false);
          if (!msg.data) return;

          const data = JSON.parse(msg.data);

          // 如果是新会话，保存会话ID
          if (isNewSession && data.conversation_id) {
            setSessions((prev) =>
              prev.map((session) => {
                if (session.id === currentSession?.id) {
                  return {
                    ...session,
                    loading: true,
                    id: data.conversation_id,
                  };
                }
                return session;
              })
            );
            setActiveSession(data.conversation_id);
          }

          switch (data.event) {
            case 'message':
              currentMessage += data.answer;
              // 更新会话中的AI消息
              setSessions((prev) =>
                prev.map((session) => {
                  if (session.id === data.conversation_id) {
                    const messages = [...(session.messages || [])];
                    const lastMessage = messages[messages.length - 1];
                    messages[messages.length - 1] = {
                      ...lastMessage,
                      loading: false,
                      content: currentMessage,
                      messageId: data.message_id,
                      timestamp: data.created_at,
                    };
                    return { ...session, messages };
                  }
                  return session;
                })
              );
              break;

            case 'message_end':
              const retrieverResources = data.metadata?.retriever_resources;

              // 获取文档ID
              const documentIds =
                retrieverResources
                  ?.map((item: any) => item.document_name?.split('_编号_')[1])
                  ?.filter((id: string) => id) || [];

              // 更新会话中的AI消息
              setSessions((prev) =>
                prev.map((session) => {
                  if (session.id === data.conversation_id) {
                    const messages = [...(session.messages || [])];
                    const lastMessage = messages[messages.length - 1];
                    messages[messages.length - 1] = {
                      ...lastMessage,
                      loading: false,
                      content: currentMessage,
                      references: {
                        links: retrieverResources?.map((item: { document_name: string, content: string }) => ({
                          title: item.document_name,
                          content: item.content,
                        })) || [],
                      },
                      messageId: data.message_id,
                      timestamp: data.created_at,
                    };
                    return { ...session, messages };
                  }
                  return session;
                })
              );

              if (documentIds.length > 0) {
                techInsightApi
                  .retreiveGraphNeo4j({
                    original_ids: JSON.stringify(documentIds),
                  })
                  .then((graph) => {
                    // 完成时，更新消息
                    setSessions((prev) =>
                      prev.map((session) => {
                        if (session.id === data.conversation_id) {
                          const messages = [...(session.messages || [])];
                          const lastMessage = messages[messages.length - 1];
                          messages[messages.length - 1] = {
                            ...lastMessage,
                            loading: false,
                            content: currentMessage,
                            references: {
                              ...lastMessage.references,
                              graphData: {
                                nodes: graph.data.nodes || [],
                                relationships: graph.data.relationships || [],
                              },
                            },
                            messageId: data.message_id,
                            timestamp: data.created_at,
                          };
                          return { ...session, messages };
                        }
                        return session;
                      })
                    );
                  });
              }
              break;
            case 'error':
              setSessions((prev) =>
                prev.map((session) => {
                  if (session.id === currentSession?.id) {
                    const messages = [...(session.messages || [])];
                    const lastMessage = messages[messages.length - 1];
                    messages[messages.length - 1] = {
                      ...lastMessage,
                      loading: false,
                      content: '抱歉，接口出错了，请重新发送！',
                      messageId: data.message_id,
                    };
                    return { ...session, messages };
                  }
                  return session;
                })
              );
              break;
          }
        },
      });
    } catch (error) {
      // 发生错误时，移除pending消息
      let currentSession = sessions.find((s) => s.id === activeSession);
      setSessions((prev) =>
        prev.map((session) => {
          if (session.id === currentSession?.id) {
            return {
              ...session,
              messages: (session.messages || []).filter((msg) => !msg.loading),
            };
          }
          return session;
        })
      );
      message.error('发送失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 添加删除会话的处理函数
  const handleDeleteSession = async (sessionId: string) => {
    const username = localStorage.getItem('username') || '';
    try {
      // 调用API删除消息记录
      await chatApi.deleteConversation(sessionId, username);

      // 如果删除的是当前活动会话，清空选中状态
      if (sessionId === activeSession) {
        setActiveSession(undefined);
      }

      // 刷新历史会话
      setLastId(null);
      setPageIds([]);
      fetchConversations(1);

      message.success('删除成功');
    } catch (error) {
      message.error('删除失败，请重试');
    }
  };

  // 当前会话的消息
  const currentMessages = useMemo(() => {
    return sessions.find((s) => s.id === activeSession)?.messages || [];
  }, [sessions, activeSession]);

  return (
    <MainLayout>
      <Layout className={styles.chatLayout}>
        <Sider width={300} className={styles.sider}>
          <Card
            title="历史记录"
            extra={
              <Button
                type="link"
                onClick={() => setActiveSession(undefined)}
                style={{ boxShadow: 'none', padding: 0 }}
              >
                新建会话
              </Button>
            }
            bordered={false}
            className={styles.historyCard}
            bodyStyle={{
              padding: 0,
              height: 'calc(100vh - 180px)',
              overflowY: 'auto',
            }}
          >
            <ChatHistory
              loading={historyLoading}
              historyList={historyList}
              onSelect={(id) => {
                setActiveSession(id);
                handleSend();
              }}
              onDelete={handleDeleteSession}
              activeId={activeSession}
              hasMore={hasMore}
              currentPage={currentPage}
              pageSize={20}
              onPageChange={handlePageChange}
            />
          </Card>
        </Sider>
        <Layout className={styles.chatContainer}>
          <Content>
            <Card
              bordered={false}
              className={styles.chatCard}
              bodyStyle={{
                height: 'calc(100vh - 180px)',
                padding: 0,
                display: 'flex',
                flexDirection: 'column',
              }}
            >
              <div className={styles.messageList}>
                {currentMessages.map((msg) => (
                  <ChatMessage key={msg.messageId} message={msg} />
                ))}
                <div ref={messagesEndRef} />
              </div>
              <div className={styles.inputArea}>
                <Space.Compact style={{ width: '100%' }}>
                  <Input
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onPressEnter={handleSend}
                    placeholder="请输入您的问题..."
                    disabled={loading}
                  />
                  <Button
                    type="primary"
                    onClick={handleSend}
                    onKeyDown={handleSend}
                    disabled={!input.trim() || loading}
                    icon={loading ? <LoadingOutlined /> : <SendOutlined />}
                  >
                    发送
                  </Button>
                </Space.Compact>
              </div>
            </Card>
          </Content>
        </Layout>
      </Layout>
    </MainLayout>
  );
};

export default AIChat;
